package com.example.springboot_ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_ruiji.common.R;
import com.example.springboot_ruiji.dao.CategoryDao;
import com.example.springboot_ruiji.exception.NameExistsException;
import com.example.springboot_ruiji.pojo.Category;
import com.example.springboot_ruiji.pojo.Employee;
import com.example.springboot_ruiji.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;

    @Override
    public R page(Integer page, Integer pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);
        Page<Category> categoryPage1 = categoryDao.selectPage(categoryPage, null);
        if (categoryPage1.getSize()==0){
            return R.error("查询失败,无数据");
        }else {
            return R.success(categoryPage1);
        }
    }

    @Override
    public R add(Category category) {
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getName,category.getName());
        Category one = categoryDao.selectOne(queryWrapper);
        if(one!=null){
            throw new NameExistsException(category.getName());
        }
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        int i = categoryDao.insert(category);
        if (i!=0) {
            return R.success("成功");
        }else {
            return R.error("失败");
        }
    }

    @Override
    public R edit(Category category) {
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getName,category.getName());
        Category one = categoryDao.selectOne(queryWrapper);
        if(one!=null){
            throw new NameExistsException(category.getName());
        }
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        int i = categoryDao.updateById(category);
        if (i!=0) {
            return R.success("成功");
        }else {
            return R.error("失败");
        }
    }

    @Override
    public void deleteById(Long id) {
        categoryDao.deleteById(id);
    }
}
